import { defineComponent, reactive, ref, h, withModifiers } from 'vue'
import pageStyle from './index.module.scss'
import { NInput, NInputGroup, NButton, NDataTable, NSpin, useMessage } from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
import dictionaryApi from '@/service/api/dictionary'
import dictionaryValueApi from '@/service/api/dictionaryValue'
import EditMl from './components/EditMl'
import Edit from './components/Edit'
import MessageBox from '@/components/nComponents/MessageBox'
interface mlItemState {
  id?: number
  name: string
}
interface tableItemState {
  id?: number
  label: string
  value: string
}
interface infoState {
  muList: mlItemState[]
  queryForm: {
    query: string
  }
}

interface tableInfoState {
  tableData: tableItemState[]
  queryForm: {
    eid: number
    query: string
  }
  listLoading: boolean
  delShow: boolean
}
export default defineComponent({
  setup() {
    const info = reactive<infoState>({
      muList: [],
      queryForm: {
        query: ''
      }
    })
    let timer: any
    const handInput = () => {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        getMu()
        clearTimeout(timer)
      }, 300)
    }
    const mlRef = ref()
    const handAddMl = (row?: mlItemState) => {
      mlRef.value.open(row || null)
    }
    const getMu = async () => {
      const { data } = await dictionaryApi.list(info.queryForm)
      info.muList = data
      if (data.length > 0 && tableInfo.queryForm.eid === -1) {
        handSelect(data[0])
      } else {
        tableInfo.listLoading = false
      }
    }
    getMu()

    const handSelect = async (el: mlItemState) => {
      if (el.id) {
        tableInfo.listLoading = true
        tableInfo.queryForm.eid = el.id
        queryData()
      }
    }

    const addRef = ref()
    const handAdd = (row?: any) => {
      addRef.value.open(
        row || {
          eid: tableInfo.queryForm.eid
        }
      )
    }

    const queryData = async () => {
      const { data } = await dictionaryValueApi.list(tableInfo.queryForm)
      tableInfo.tableData = data
      tableInfo.listLoading = false
    }

    const tableInfo = reactive<tableInfoState>({
      tableData: [],
      queryForm: {
        eid: -1,
        query: ''
      },
      listLoading: false,
      delShow: false
    })
    const columns: DataTableColumns<any> = [
      {
        title: 'label',
        key: 'label'
      },
      {
        title: 'value',
        key: 'value'
      },
      {
        title: '操作',
        key: 'total',
        width: 140,
        render(row, index) {
          return h('div', [
            h(
              NButton,
              {
                size: 'small',
                type: 'warning',
                class: 'ml10',
                onClick: () => handAdd(row)
              },
              { default: () => '编辑' }
            ),
            h(
              NButton,
              {
                size: 'small',
                class: 'ml10',
                type: 'error',
                onClick: () => handDel(index)
              },
              { default: () => '删除' }
            )
          ])
        }
      }
    ]
    /**
     *  删除
     * */
    const toast = useMessage()
    const delLoading = ref(false)
    let oldIndex = -1
    let oldType = 'data'
    const handDel = (index: number, type = 'data') => {
      oldType = type
      oldIndex = index
      tableInfo.delShow = true
    }
    const handConfirm = async () => {
      delLoading.value = true
      if (oldType === 'data') {
        const { code, message } = await dictionaryValueApi.dels({
          ids: [tableInfo.tableData[oldIndex].id]
        })
        delLoading.value = false
        if (code !== 200) {
          toast.error(message)
          return
        }
      } else {
        const { code, message } = await dictionaryApi.dels({
          ids: [info.muList[oldIndex].id]
        })
        delLoading.value = false
        if (code !== 200) {
          toast.error(message)
          return
        }
      }

      toast.success('删除成功')
      tableInfo.delShow = false
      queryData()
    }

    const boxSlot = {
      header: () => (
        <div>
          <div class="title">温馨提示</div>
        </div>
      ),
      default: () => (
        <>
          <div class={pageStyle.delBox}>
            <div class="pt-[10px] pb-[10px]">
              <i class="esayIcon esayIcon-jinggao"></i>
              <span class="tip">确认要删除选中数据吗?</span>
            </div>
            <div class="btns flex align-center justify-end">
              <NButton
                secondary
                onClick={() => {
                  tableInfo.delShow = false
                }}
              >
                取消
              </NButton>
              <NButton style={{ marginLeft: '10px' }} type="primary" onClick={handConfirm}>
                {delLoading.value && (
                  <NSpin
                    class="mr-[10px]"
                    size={15}
                    stroke="#fff"
                    v-slots={{
                      icon: () => <i class="esayIcon esayIcon-a-jiazaizhongdaxiao text-white"></i>
                    }}
                  />
                )}
                <span>确认删除</span>
              </NButton>
            </div>
          </div>
        </>
      )
    }
    return () => (
      <>
        <div class={pageStyle.dictionary}>
          <div class="dictionary-left">
            <div>
              <NInputGroup>
                <NInput
                  placeholder="请输入关键字"
                  v-model:value={info.queryForm.query}
                  onInput={handInput}
                />
                <NButton onClick={() => handAddMl()}>
                  <i class="esayIcon esayIcon-tianjiawenjianjia"></i>
                </NButton>
              </NInputGroup>
            </div>
            <div class="enum">
              {info.muList.map((el: mlItemState, index: number) => (
                <div
                  class={`cell cursor-pointer ${
                    tableInfo.queryForm.eid === el.id && 'cell-active'
                  }`}
                  onClick={withModifiers(() => {
                    handSelect(el)
                  }, ['stop'])}
                >
                  <div class="name u-line-1">{el.name}</div>
                  <div
                    class="close"
                    onClick={withModifiers(() => {
                      handAddMl(el)
                    }, ['stop'])}
                  >
                    <i class="esayIcon esayIcon-bianji_2"></i>
                  </div>
                  <div
                    class="close"
                    onClick={withModifiers(() => {
                      handDel(index, 'ml')
                    }, ['stop'])}
                  >
                    <i class="esayIcon esayIcon-shanchu2"></i>
                  </div>
                </div>
              ))}
            </div>
          </div>
          <div class="dictionary-right">
            <div class="pb20 flex justify-between">
              <div>
                <NButton type="success" onClick={() => handAdd()}>
                  <i class="esayIcon esayIcon-tianjiawenjianjia"></i>
                  <span class="ml-[10px]">添加</span>
                </NButton>
              </div>
              <div class="flex">
                <NInput
                  placeholder="请输入关键字"
                  v-model:value={tableInfo.queryForm.query}
                  clearable
                />
                <div class="ml-[5px]">
                  <NButton type="success" onClick={() => queryData()}>
                    <span>搜索</span>
                  </NButton>
                </div>
              </div>
            </div>
            <NDataTable
              class="flex-1"
              flex-height
              striped
              loading={tableInfo.listLoading}
              columns={columns}
              data={tableInfo.tableData}
              pagination={false}
            />
          </div>
        </div>
        <MessageBox width={'400px'} v-model={tableInfo.delShow} isClose={false} v-slots={boxSlot} />
        <EditMl ref={mlRef} onSuccess={getMu} />
        <Edit ref={addRef} onSuccess={queryData} />
      </>
    )
  }
})
